﻿using System;
using PEProtocol;
using UnityEngine;
using UnityEngine.SceneManagement;

public class StageSystem : ILogic
{
    private PERoot mRoot;
    private UISvc mUISvc;
    private ResSvc mResSvc;
    private NetSvc mNetSvc;
    private int mStageID;
    private StageConfig mConfig;

    public int StageID
    {
        get => mStageID;
        set => mStageID = value;
    }

    private Action mLoadStageDoneAction;

    public void Init()
    {
        this.Log("StageSystem Init...");
        mRoot = PERoot.Instance;
        mUISvc = mRoot.UIService;
        mResSvc = mRoot.ResService;
        mNetSvc = mRoot.NetService;
        
        mNetSvc.AddMsgHandle(CMD.NtfEnterStage,NtfEnterStage);
        
       
    }

    public void Tick()
    {
       
    }

    public void UnInit()
    {
        this.Log("StageSystem UnInit...");
    }

    public void NtfEnterStage(NetMsg msg)
    {
        EnterGameStage(msg.NtfEnterStage.StageID, () =>
        {
            mRoot.EnterGameMode(XlsConfigTool.GetStageConfig(msg.NtfEnterStage.StageID).PlayMode);
        });
    }

    public void EnterGameStage(int stageID, Action stageAction)
    {
        this.StageID = stageID;
        this.mLoadStageDoneAction = stageAction;
        mConfig = XlsConfigTool.GetStageConfig(stageID);
        if (mConfig != null)
        {
            if (mConfig.IsGhost) //镜像场景
            {
            }
            else
            {
                mUISvc.SetLoading(0, true);
            }

            LoadScene(mConfig.SceneName);
        }
    }

    public void LoadScene(string sceneName)
    {
        mResSvc.LoadSceneAsync(sceneName, (process) => { UpdateLoadingProcess(process); },
            () => { UpdateLoadingProcess(1); });
    }

    public void UpdateLoadingProcess(float process)
    {
        int loadProcessPercent = (int)process * 100;
        if (mLoadStageDoneAction != null && !mConfig.IsGhost) //镜像副本
        {
            mUISvc.SetLoading(loadProcessPercent);
        }
        if (loadProcessPercent == 100)
        {
            mLoadStageDoneAction?.Invoke();
            mLoadStageDoneAction = null;
        }
        
    }
}